<template>
    <!-- 内容区域 -->
    <div class="flex-1 overflow-auto pb-6 px-20" :style="{ minWidth: `${minContentWidth}px` }">
        <div v-if="loading" class="flex justify-center items-center h-full">
            <i class="fa fa-spinner fa-spin text-3xl text-gray-400"></i>
        </div>
        <div v-else-if="error" class="p-6 bg-red-50 border border-red-200 rounded-lg">
            <h2 class="text-xl font-bold text-red-700 mb-2">加载失败</h2>
            <p class="text-red-600">{{ error }}</p>
        </div>
        <div v-else class="max-w-none">
            <div v-show="status.edit">
                <MarkdownEditor :content="origin_content" @update="updateContent"></MarkdownEditor>
            </div>
            <div v-show="status.preview">
                <MarkdownPreview :content="preview_content"></MarkdownPreview>
            </div>
        </div>
    </div>
</template>

<script setup>

const status = reactive({
    edit: false,
    preview: true
})
const loading = ref(false)
const error = ref('')
const minContentWidth = 300

const props = defineProps({
    content: {
        type: String,
        required: true
    }
})
const origin_content = ref(props.content)
const preview_content = ref(props.content)

// 接收父组件的 content
watch(
    () => props.content,
    (newValue) => {
        origin_content.value = newValue
        preview_content.value = newValue
    }
)

// 接收子组件的 content
const updateContent = (newContent) => {
    origin_content.value = newContent
    preview_content.value = newContent
}


onMounted(async ()=>{
    window.addEventListener('keydown', toggleEditPreviewByKeydown)
})
onUnmounted(()=>{
    window.removeEventListener('keydown', toggleEditPreviewByKeydown)
})

/**
 * 切换编辑和预览
 */
const toggleEditPreview = async () => {
    if (status.edit) { // 编辑 -> 预览
        status.edit = false
        status.preview = true
    } else { // 预览 -> 编辑
        status.edit = true
        status.preview = false
    }
}

const { Message } = useMessageBox()
const { saveMarkdown } = useApi()

const toggleEditPreviewByKeydown = async(event) => {
    // ctrl + p: 切换
    if (event.ctrlKey && event.key === 'p') {
        event.preventDefault();
        toggleEditPreview()
    }
    // ctrl + s: 保存
    else if (event.ctrlKey && event.key === 's') {
        event.preventDefault();
        const response = await saveMarkdown({
            content: origin_content.value,
            path: useState('path').value
        })
        if (response.code != 200) {
            Message.error(response.msg)
        } else {
            Message.success('保存成功', { width: 'auto' })
        }
    } 
}

</script>

<style scoped></style>